<template>
    <div style="margin: 20px;">
        <div>
            <Row style="margin-bottom: 25px;">
                <Col span="5" style="margin-right: 20px;">
                    <Input v-model="studentName" clearable placeholder="请输入学生姓名..."/>
                </Col>
                <Col span="2">
                    <Button type="primary" shape="circle" icon="ios-search" @click="search()">搜索</Button>
                </Col>
            </Row>
        </div>
        <!--列表model-->
        <div>
            <ul style="list-style: none">
                <li>
                    <Button type="primary" icon="plus-round" @click="insertStudent()">新建</Button>
                    <Button type="error" icon="trash-a" @click="del()">删除</Button>
                </li>
                <li>
                    <div style="padding: 10px 0;position: relative;">
                        <Spin fix v-if="loadingTable">
                            <Icon type="load-c" size=18 class="demo-spin-icon-load"></Icon>
                            <div>Loading</div>
                        </Spin>
                        <Table border :columns="studentColumn" :data="studentData" @on-selection-change="s=>{change(s)}"></Table>
                    </div>
                </li>
                <li>
                    <div style="text-align: right;">
                        <Page :total="total" :page-size="pageInfo.pageSize" show-elevator show-total
                              @on-change="e=>{pageSearch(e)}"></Page>
                    </div>
                </li>
            </ul>
        </div>
        <!--添加modal-->
        <Modal :mask-closable="false" :visible.sync="newModal" :loading="loading" v-model="newModal" width="600"
               title="新建" @on-ok="newOk('studentNew')" @on-cancel="cancel(0)">
            <Form ref="studentNew" :model="studentNew" :rules="ruleNew" :label-width="80">
                <Row>
                    <Form-item label="学生编号:" prop="studentNum">
                        <Input v-model="studentNew.studentNum" number style="width: 90%"/>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="所属班级:" prop="classNum">
                        <Select v-model="studentNew.classNum" filterable clearable placeholder="请选择班级名称..." style="width: 90%">
                            <Option v-for="item in classList" :value="item.value" :key="item.value">{{ item.label }}
                            </Option>
                        </Select>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="学生姓名:" prop="studentName">
                        <Input v-model="studentNew.studentName" style="width: 90%"/>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="学生性别:" prop="studentSex">
                        <RadioGroup v-model="studentNew.studentSex">
                            <Radio label="1">男</Radio>
                            <Radio label="2">女</Radio>
                        </RadioGroup>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="学生生日:" prop="studentBirthday">
                        <Date-picker :options="optionsBirthday" type="datetime" v-model="studentNew.studentBirthday" format="yyyy-MM-dd"
                                     placeholder="请选择出生日期" style="width:90%;"></Date-picker>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="班级排名:" prop="classRank">
                        <Input v-model="studentNew.classRank" number style="width: 90%"/>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="年级排名:" prop="gradeRank">
                        <Input v-model="studentNew.gradeRank" number style="width: 90%"/>
                    </Form-item>
                </Row>
            </Form>
        </Modal>
        <!--修改modal-->
        <Modal :mask-closable="false" :visible.sync="modifyModal" :loading="loading" v-model="modifyModal" width="600"
               title="编辑" @on-ok="modifyOk('studentModify')" @on-cancel="cancel(1)">
            <Form ref="studentModify" :model="studentModify" :rules="ruleModify" :label-width="80">
                <Row>
                    <Form-item label="学生编号:" prop="studentNum">
                        <Input v-model="studentModify.studentNum" number style="width: 90%"/>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="学生姓名:" prop="studentName">
                        <Input v-model="studentModify.studentName" style="width: 90%"/>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="所属班级:" prop="classNum">
                        <Select v-model="studentModify.classNum" filterable clearable placeholder="请选择班级名称..." style="width: 90%">
                            <Option v-for="item in classList" :value="item.value" :key="item.value">{{ item.label }}
                            </Option>
                        </Select>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="学生性别:" prop="studentSex">
                        <RadioGroup v-model="studentModify.studentSex">
                            <Radio label="1">男</Radio>
                            <Radio label="2">女</Radio>
                        </RadioGroup>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="学生生日:" prop="studentBirthday">
                        <Date-picker :options="optionsBirthday" type="datetime" v-model="studentModify.studentBirthday" format="yyyy-MM-dd"
                                     placeholder="请选择出生日期" style="width:90%;"></Date-picker>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="班级排名:" prop="classRank">
                        <Input v-model="studentModify.classRank" number style="width: 90%"/>
                    </Form-item>
                </Row>
                <Row>
                    <Form-item label="年级排名:" prop="gradeRank">
                        <Input v-model="studentModify.gradeRank" number style="width: 90%"/>
                    </Form-item>
                </Row>
            </Form>
        </Modal>
    </div>
</template>
<script>
    import {formatDate} from '../../utilJs/formatDate';
    import _ from 'lodash';
    export default {
        data() {
            const validateStudentNumRepNew = (rule, value, callback) => {
                this.axios({
                    method: 'get',
                    url: '/student/checkStudentNum',
                    params: {
                        'studentNum':this.studentNew.studentNum
                    }
                }).then(function (response) {
                    if (response.data.msg && response.data.msg == 1) {
                        callback(new Error('学号重复'));
                    }else {
                        callback();
                    }
                }.bind(this)).catch(function (error) {
                    //alert(error);
                });
            };
            const validateStudentNum = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('学生编号不能为空'));
                }
                // 模拟异步验证效果
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字类型'));
                    } else {
                        if (value < 0) {
                            callback(new Error('编号必须大于0'));
                        } else if(value > 100000) {
                            callback(new Error('编号必须小于100000'));
                        } else {
                            callback();
                        }
                    }
                }, 1000);
            };
            const validateClassRank = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('班级排名'));
                }
                // 模拟异步验证效果
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字类型'));
                    } else {
                        if (value < 0) {
                            callback(new Error('排名必须大于0'));
                        } else if(value > 1000) {
                            callback(new Error('编号必须小于1000'));
                        } else {
                            callback();
                        }
                    }
                }, 1000);
            };
            const validateGradeRank = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('年级排名'));
                }
                // 模拟异步验证效果
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字类型'));
                    } else {
                        if (value < 0) {
                            callback(new Error('排名必须大于0'));
                        } else if(value > 1000) {
                            callback(new Error('编号必须小于1000'));
                        } else {
                            callback();
                        }
                    }
                }, 1000);
            };
            return {
                loadingTable:true,
                studentName: null,
                count: null,
                groupId: null,
                newModal: false,
                modifyModal: false,
                total: 0,
                loading: true,
                pageInfo: {
                    page: 0,
                    pageSize: 10,
                    studentName: null
                },
                classList: [],
                optionsBirthday: {
                    disabledDate (date) {
                        return date && date.valueOf() > Date.now() - 86400000;
                    }
                },
                /*student实体*/
                student: {
                    studentNum: null,
                    classNum: null,
                    studentName: null,
                    studentSex: null,
                    studentBirthday: null,
                    classRank: null,
                    gradeRank: null
                },
                /*用于添加的student实体*/
                studentNew: {
                    studentNum: null,
                    classNum: null,
                    studentName: null,
                    studentSex: null,
                    studentBirthday: null,
                    classRank: null,
                    gradeRank: null
                },
                /*用于修改的student实体*/
                studentModify: {
                    studentNum: null,
                    classNum: null,
                    studentName: null,
                    studentSex: null,
                    studentBirthday: null,
                    classRank: null,
                    gradeRank: null
                },
                /**********************变量定义end**********************/
                /**********************页面校验start**********************/
                ruleNew: {
                    studentNum: [
                        {validator: validateStudentNum, trigger: 'blur'},
                        {validator: validateStudentNumRepNew, trigger: 'blur'}
                    ],
                    studentName: [
                        { type: 'string', required: true, message: '输入学生姓名', trigger: 'blur'},
                        { type:'string',max: 10, message: '最大长度为10个字符', trigger: 'blur' }
                    ],
                    studentSex: [
                        {required: true, message: '选择性别', trigger: 'change'}
                    ],
                    studentBirthday: [
                        {type: 'date', required: true, message: '输入学生生日', trigger: 'change'}
                    ],
                    classRank: [
                        {validator: validateClassRank, trigger: 'blur'}
                    ],
                    gradeRank: [
                        {validator: validateGradeRank, trigger: 'blur'}
                    ]
                },
                ruleModify: {
                    studentNum: [
                        {validator: validateStudentNum, trigger: 'blur'}
                    ],
                    studentName: [
                        { type: 'string', required: true, message: '输入学生姓名', trigger: 'blur'},
                        { type:'string',max: 10, message: '最大长度为10个字符', trigger: 'blur' }
                    ],
                    studentSex: [
                        {required: true, message: '选择性别', trigger: 'change'}
                    ],
                    studentBirthday: [
                        {type: 'date', required: true, message: '输入学生生日', trigger: 'change'}
                    ],
                    classRank: [
                        {validator: validateClassRank, trigger: 'blur'}
                    ],
                    gradeRank: [
                        {validator: validateGradeRank, trigger: 'blur'}
                    ]
                },
                /**********************页面校验end**********************/
                /**********************列表显示start**********************/
                /*生产类型表显示字段*/
                studentColumn: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {
                        title: '学生编号',
                        key: 'studentNum',
                        align: 'center'
                    },
                    {
                        title: '所属班级',
                        key: 'name',
                        align: 'center'
                    },
                    {
                        title: '学生姓名',
                        key: 'studentName',
                        align: 'center'
                    },
                    {
                        title: '学生性别',
                        key: 'studentSex',
                        align: 'center',
                        render: (h, params) => {
                            let state = params.row.studentSex == 1 ? "男" : "女";
                            let color = params.row.studentSex == 1 ? "#3cc472" : "gray";
                            return h("span", {
                                    style: {
                                        color: color,
                                    }
                                },
                                state
                            );
                        }
                    },
                    {
                        title: '学生生日',
                        key: 'studentBirthday',
                        align: 'center',
                        render: (h,params)=>{
                            return h('div',
                                formatDate(new Date(params.row.studentBirthday),'yyyy-MM-dd')
                            )
                        }
                    },
                    {
                        title: '班级排名',
                        key: 'classRank',
                        align: 'center'
                    },
                    {
                        title: '年级排名',
                        key: 'gradeRank',
                        align: 'center'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        align: 'center',
                        width:160,
                        render: (h, params) => {
                            let btnArr = [];
                            btnArr.push(
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        margin: '3px',
                                        color: '#2d8cf0',
                                        backgroundColor: '#ffffff',
                                        border: '1px solid #2d8cf0'
                                    },
                                    on: {
                                        click: () => {
                                        this.relationEdit(params.row)
                                        }
                                     }
                                }, '编辑'),
                            );
                            btnArr.push(
                                h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        margin: '3px',
                                        color: '#ed3f14',
                                        backgroundColor: '#ffffff',
                                        border: '1px solid #ed3f14'
                                    },
                                    on: {
                                        click: () => {
                                            this.setSingleGroupId(params.row.studentNum);
                                            this.del();
                                        }
                                    }
                                 }, '删除')
                            );
                        return h('div', btnArr);
                        }
                    }
                ],
                /*生产类型表数据*/
                studentData: []
                /**********************列表显示start**********************/
            }
        },
        mounted() {
            /*页面初始化调用方法*/
            this.getTable(this.pageInfo);
            this.getAllClass();
        },
        methods: {
            /*pageInfo实体初始化*/
            initPageInfo() {
                this.pageInfo.page = 0;
                this.pageInfo.pageSize = 10;
                this.pageInfo.studentName = null;
            },
            /*student实体初始化*/
            initStudent() {
                this.student.studentNum = null;
                this.student.classNum = null;
                this.student.studentName = null;
                this.student.studentSex = null;
                this.student.studentBirthday = null;
                this.student.classRank = null;
                this.student.gradeRank = null;
            },
            /*studentNew实体初始化*/
            initStudentNew(){
                this.studentNew.studentNum = null;
                this.studentNew.classNum = null;
                this.studentNew.studentName = null;
                this.studentNew.studentSex = null;
                this.studentNew.studentBirthday = null;
                this.studentNew.classRank = null;
                this.studentNew.gradeRank = null;
            },
            /*studentModify实体初始化*/
            initStudentModify(){
                this.studentModify.studentNum = null;
                this.studentModify.classNum = null;
                this.studentModify.studentName = null;
                this.studentModify.studentSex = null;
                this.studentModify.studentBirthday = null;
                this.studentModify.classRank = null;
                this.studentModify.gradeRank = null;
            },
            /*student设置*/
            studentSet(e) {
                this.student.studentNum = e.studentNum;
                this.student.classNum = e.classNum;
                this.student.studentName = e.studentName;
                this.student.studentSex = e.studentSex;
                this.student.studentBirthday = e.studentBirthday;
                this.student.classRank = e.classRank;
                this.student.gradeRank = e.gradeRank;
            },
            /*studentNew设置*/
            studentNewSet(e){
                this.studentNew.studentNum = e.studentNum;
                this.studentNew.classNum = e.classNum;
                this.studentNew.studentName = e.studentName;
                this.studentNew.studentSex = e.studentSex;
                this.studentNew.studentBirthday = e.studentBirthday;
                this.studentNew.classRank = e.classRank;
                this.studentNew.gradeRank = e.gradeRank;
            },
            /*studentModify设置*/
            studentModifySet(e){
                this.studentModify.studentNum = e.studentNum;
                this.studentModify.classNum = e.classNum;
                this.studentModify.studentName = e.studentName;
                this.studentModify.studentSex = e.studentSex;
                this.studentModify.studentBirthday = e.studentBirthday;
                this.studentModify.classRank = e.classRank;
                this.studentModify.gradeRank = e.gradeRank;
            },
            /*获取列表数据*/
            getTable(e) {
                this.loadingTable = true;
                this.axios({
                    method: 'get',
                    url: '/student',
                    params: {
                        page: e.page,
                        pageSize: e.pageSize,
                        studentName: e.studentName
                    }
                }).then(function (response) {
                    // 鲁大师数组扁平化
                    _.flatMap(response.data.data, function(n) {
                        n.name = n.classEntity.className;
                        return n;
                    });
                    this.studentData = response.data.data;
                    this.total = response.data.totalCount;
                    this.loadingTable = false;
                    this.groupId = null;
                }.bind(this)).catch(function (error) {
                    //alert(error);
                });
            },
            /*搜索按钮点击事件*/
            search() {
                this.pageInfo.studentName = this.studentName;
                this.getTable(this.pageInfo);
            },
            /*分页点击事件*/
            pageSearch(e) {
                this.pageInfo.page = e - 1;
                this.getTable(this.pageInfo);
            },
            /*新建点击触发事件*/
            insertStudent() {
                this.$refs['studentNew'].resetFields();
                this.newModal = true;
                this.studentData.sort();
                this.count = 0;
                this.groupId = null;
            },
            /*新建modal的newOk点击事件*/
            newOk(studentNew) {
                this.$refs[studentNew].validate((valid) => {
                    if (valid) {
                        this.initStudent();
                        this.studentSet(this.studentNew);
                        this.axios({
                            method: 'post',
                            url: '/student',
                            data: this.student
                        }).then(function (response) {
                            if (response.data && response.data.msg == 'success') {
                                this.$Message.info('新建成功');
                            }
                            this.initStudent();
                            this.getTable(this.pageInfo);
                        }.bind(this)).catch(function (error) {
                            //alert(error);
                        });
                        this.newModal = false;
                    } else {
                        setTimeout(() => {
                            this.loading = false;
                            this.$nextTick(() => {
                                this.loading = true;
                            });
                        }, 1000);
                    }
                })
            },
            /*点击修改时*/
            relationEdit(e){
                this.$refs['studentModify'].resetFields();
                this.initStudentModify();
                this.studentModifySet(e);
                this.modifyModal = true;
            },
            /*修改modal的modifyOk点击事件*/
            modifyOk(studentModify) {
                this.$refs[studentModify].validate((valid) => {
                    if (valid) {
                        this.initStudent();
                        this.studentSet(this.studentModify);
                        this.axios({
                            method: 'put',
                            url: '/student',
                            data: this.student
                        }).then(function (response) {
                            if (response.data && response.data.msg == 'success') {
                                this.$Message.info('修改成功');
                            }
                            this.initStudentModify();
                            this.getTable(this.pageInfo);
                        }.bind(this)).catch(function (error) {
                            //alert(error);
                        });
                        this.modifyModal = false;
                    } else {
                        this.$Message.error('表单验证失败!');
                        setTimeout(() => {
                            this.loading = false;
                            this.$nextTick(() => {
                                this.loading = true;
                            });
                        }, 1000);
                    }
                })
            },
            /*modal的cancel点击事件*/
            cancel(val) {
                if (val == 0) {
                    this.$Message.info('新增操作取消');
                }
                if (val == 1) {
                    this.$Message.info('编辑操作取消');
                }

            },
            /*table选择后触发事件*/
            change(e) {
                this.setGroupId(e);
            },
            /*通过选中的行设置groupId的值*/
            setGroupId(e) {
                this.groupId = [];
                this.count = e.length;
                for (var i = 0; i <= e.length - 1; i++) {
                    this.groupId.push(e[i].studentNum);
                }
            },
            setSingleGroupId(e){
                this.groupId = [];
                this.count = 1;
                this.groupId.push(e);
            },
            /*删除table中选中的数据*/
            del() {
                if(this.groupId != null && this.groupId != ""){
                    this.$Modal.confirm({
                        title: '信息确认',
                        content: '<p>您确定要删除吗?</p>',
                        onOk: () => {
                            this.axios({
                                method: 'delete',
                                url: '/student',
                                data: this.groupId
                            }).then(function (response) {
                                if (response.data && response.data.msg == 'success') {
                                    this.$Message.info('删除成功');
                                }
                                this.getTable(this.pageInfo);
                                this.groupId = null;
                                this.count = 0;
                            }.bind(this)).catch(function (error) {
                                //alert(error);
                            });
                        },
                        onCancel: () => {
                            this.$Message.info('删除记录取消!');
                        }
                    });
                }else{
                    this.$Message.info('至少选择一条记录!');
                }
            },
            getAllClass() {
                this.axios({
                    method: 'get',
                    url: '/class/getAllClasses'
                }).then(function (response) {
                    this.classList = [];
                    var listTemp = response.data;
                    for (var i = 0; i < listTemp.length; i++) {
                        this.classList.push({
                            "value": listTemp[i].classNum,
                            "label": listTemp[i].className
                        });
                    }
                }.bind(this)).catch(function (error) {
                    //alert(error);
                });
            }
        }
    }
</script>
